package com.wolfking.jeesite.freemarker.method;

import com.wolfking.jeesite.freemarker.FreemarkerMethod;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * freemarker的权限的标签
 * <p>
 *
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年4月28日下午3:50:30
 * @版权 归wolfking所有
 */
@Slf4j
@FreemarkerMethod("cookieValue")
public class CookieValueMethod implements TemplateMethodModelEx {

    @Override
    public Object exec(List list) throws TemplateModelException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        Cookie[] cookies = request.getCookies();
        String cookie = list.get(0).toString();
        String defaultValue = list.get(1).toString();
        if (cookies != null) {
            for (Cookie c : cookies) {
                if (c.getName().equals(cookie) && StringUtils.isNotBlank(c.getValue())) {
                    return c.getValue();
                }
            }
        }
        return defaultValue;
    }
}
